package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"video_demo/api"
	"video_demo/config"
)

func main() {
	// 创建 Gin 实例
	router := gin.Default()
	// 配置文件解析
	cfg := config.SysConfig
	// 全局中间件
	router.Use(CORSMiddleware())
	// 初始化路由
	api.Init(router)

	//启动服务
	if err := router.Run(fmt.Sprintf(":%d", cfg.Server.Port)); err != nil {
		panic("服务启动失败")
	}
}

func CORSMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 获取请求的Origin头
		origin := c.Request.Header.Get("Origin")

		// 允许的域名列表
		allowedOrigins := map[string]bool{
			"http://localhost:63342":   true, // 开发环境
			"http://60.205.6.131:8018": true, // 生产环境
		}

		// 如果请求的Origin在允许列表中，则设置响应头
		if allowedOrigins[origin] {
			c.Writer.Header().Set("Access-Control-Allow-Origin", origin)
			c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
			c.Writer.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
			c.Writer.Header().Set("Access-Control-Allow-Headers",
				"Content-Type, Authorization, X-Requested-With, Cache-Control")
			c.Writer.Header().Set("Access-Control-Expose-Headers",
				"Content-Length, Content-Range")
			c.Writer.Header().Set("Access-Control-Max-Age", "86400")
		}

		// 处理预检请求
		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(http.StatusNoContent)
			return
		}

		c.Next()
	}
}
